package com.tyj.gulimall.product.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.tyj.gulimall.product.service.CategoryBrandRelationService;
import com.tyj.gulimall.product.vo.web.Catalog2Vo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tyj.common.utils.PageUtils;
import com.tyj.common.utils.Query;
import com.tyj.gulimall.product.dao.CategoryDao;
import com.tyj.gulimall.product.entity.CategoryEntity;
import com.tyj.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> getCategoryList() {
        List<CategoryEntity> entities = baseMapper.selectList(null);
        List<CategoryEntity> collect = entities.stream().filter((categoryEntity) ->
                //因为0是根类 所以要取出根类
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {  //map 将字符串接收改为对象接收
            menu.setChildren(getChildrens(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return collect;
    }

    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> level1Meus = all.stream().filter(categoryEntity -> {
            //找到谁的父类等于该根类
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return level1Meus;

    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath); //倒序排序
        return (Long[]) paths.toArray(new Long[parentPath.size()]);
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        paths.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 修改三级分类数据
     * @param category
     */                                 //不加'号会以表达式解析 加'号以字符串解析
    //@CacheEvict(value = "category",key ="'getLevel1Category'") //使用缓存失效 删除缓存
//    @Caching(evict = {   //删除多个缓存
//            @CacheEvict(value = "category",key ="'getLevel1Category'"),
//            @CacheEvict(value = "category",key ="'getCategoryJson'")
//
//    })
//    @CachePut 双写模式需要使用,但我们现在是缓存失效模式
    @CacheEvict(value = "category",allEntries = true) //同上操作
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        if (!StringUtils.isEmpty(category.getName())) {
            categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
        }
    }
    //想自定义缓存的key
    //设置缓存的存活时间 需要在配置文件中
    //将数据保存为json格式
                //指定缓存分区设置缓存名字(一般按照业务类型)  category::SimpleKey [] (SimpleKey []是自主生成的键)
    @Cacheable(value = "category",key = "#root.method.name",sync = true) //代表当前方法结果需要缓存,如果缓存中有,方法不调用,用如果没有调  sync = true避免缓存击穿
    @Override
    public List<CategoryEntity> getLevel1Category() {
        System.out.println("缓存开始执行");
        return this.baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Cacheable(value = "category",key = "#root.method.name",sync = true)
    @Override
    public Map<String, List<Catalog2Vo>> getCategoryJson() {
        List<CategoryEntity> category = baseMapper.selectList(null);
        //1查出所有1分类
        List<CategoryEntity> level1Category = getParent_cid(category, 0L);
        //封装数据
        Map<String, List<Catalog2Vo>> map = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个一级分类查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(category, v.getCatId());
            List<Catalog2Vo> collect = null;
            if (categoryEntities != null) {
                collect = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类
                    List<CategoryEntity> catalogLevel3 = getParent_cid(category, l2.getCatId());
                    if (catalogLevel3 != null) {
                        //封装三级分类的指定格式
                        List<Catalog2Vo.Catalog3Vo> collect1 = catalogLevel3.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect1);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        return map;
    }

    /**
     * redisson分布式锁版
     */
    public Map<String, List<Catalog2Vo>> getCategoryJsonFromDBWithRedissonLock() {

        //获取分布式锁
        RLock lock = redisson.getLock("categoryJson-lock");
        lock.lock();  //加锁
        Map<String, List<Catalog2Vo>> dataFromDB;
        try {
            dataFromDB = getCategoryJsonFromDBWithRedis();
        } finally {
            lock.unlock();
        }
        return dataFromDB;

    }

    /**
     * redis分布式锁版
     */
    public Map<String, List<Catalog2Vo>> getCategoryJsonFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        Boolean lock = ops.setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Catalog2Vo>> dataFromDB;
            try {
                dataFromDB = getCategoryJsonFromDBWithRedis();
            } finally {
                String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n" +
                        "    return redis.call(\"del\",KEYS[1])\n" +
                        "else\n" +
                        "    return 0\n" +
                        "end";
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }
            return dataFromDB;
        } else {
            return getCategoryJsonFromDBWithRedisLock(); //自旋方式
        }
    }


    /**
     * 查询三级分类 redis版
     *
     * @return
     */
    public Map<String, List<Catalog2Vo>> getCategoryJsonFromDBWithRedis() {
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //缓存没有,查询数据库
            Map<String, List<Catalog2Vo>> categoryJsonFromDB = getCategoryJsonFromDB();
            //查到的数据放入缓存
            redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(categoryJsonFromDB));
            log.info("放入缓存成功");
            return categoryJsonFromDB;
        }
        //转为我们制定的对象.
        log.info("从缓存拿取成功");
        Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
        });
        return result;
    }

    /**
     * 查询三级分类数据库版
     * 注意 这里在压力测试时报出内存溢出异常
     * 原因 io.lettuce:lettuce-core:5.2.1.RELEASE jar包底层操作netty时产生不当
     * 在maven出排除该jar包 使用jedis
     */
    public Map<String, List<Catalog2Vo>> getCategoryJsonFromDB() {
        /**
         * 将数据库多次查询变为一次
         */
        synchronized (this) {
            return getDataFromDB();

        }
    }

    private Map<String, List<Catalog2Vo>> getDataFromDB() {
        //双重效验再次确认缓存
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //缓存没有,查询数据库
            Map<String, List<Catalog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2Vo>>>() {
            });
            return result;
        }
        log.info("查询数据库");
        List<CategoryEntity> category = baseMapper.selectList(null);
        //1查出所有1分类
        List<CategoryEntity> level1Category = getParent_cid(category, 0L);
        //封装数据
        Map<String, List<Catalog2Vo>> map = level1Category.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //每一个一级分类查到这个一级分类的二级分类
            List<CategoryEntity> categoryEntities = getParent_cid(category, v.getCatId());
            List<Catalog2Vo> collect = null;
            if (categoryEntities != null) {
                collect = categoryEntities.stream().map(l2 -> {
                    Catalog2Vo catalog2Vo = new Catalog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //找到当前二级分类的三级分类
                    List<CategoryEntity> catalogLevel3 = getParent_cid(category, l2.getCatId());
                    if (catalogLevel3 != null) {
                        //封装三级分类的指定格式
                        List<Catalog2Vo.Catalog3Vo> collect1 = catalogLevel3.stream().map(l3 -> {
                            Catalog2Vo.Catalog3Vo catalog3Vo = new Catalog2Vo.Catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catalog2Vo.setCatalog3List(collect1);
                    }
                    return catalog2Vo;
                }).collect(Collectors.toList());
            }
            return collect;
        }));
        redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(map), 1, TimeUnit.DAYS);
        return map;
    }


    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_id) {
        return selectList.stream().filter(item -> item.getParentCid() == parent_id).collect(Collectors.toList());
    }




}